import axios from 'axios'
import qs from 'qs'
import router from '../router'
// axios 配置
var instance = axios.create({
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  timeout: 30000,
  baseURL: 'http://192.168.0.183:8200'
  // baseURL:'https://test.chinartn.com',
  // baseURL:'https://www.chinartn.com'
})
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 拦截重复请求
// 声明一个数组用于存储每个ajax请求的取消函数和ajax标识
let pending = []
let CancelToken = axios.CancelToken
let removeRepeatUrl = (config) => {
  let comValue = config.method == 'get' ? qs.stringify(config.params) : qs.stringify(config.data)
  for (let p in pending) {
    // 当前请求在数组中存在时执行函数体
    if (pending[p].u === config.url + '&' + config.method + '&' + comValue) {
      pending.splice(p, 1)
    }
  }
}
let saveRepeatUrl = (config) => {
  let comValue = config.method == 'get' ? qs.stringify(config.params) : qs.stringify(config.data)
  config.cancelToken = new CancelToken((c) => {
    pending.push({ u: config.url + '&' + config.method + '&' + comValue, f: c })
  })
}
// 添加请求拦截器
instance.interceptors.request.use(config => {
  // 在发送请求之前做些什么，比如传token
  removeRepeatUrl(config)
  saveRepeatUrl(config)
  return config
}, error => {
  // 对请求错误做些什么
  console.log(error) // for debug
  return Promise.reject(error)
})
// 添加响应拦截器
instance.interceptors.response.use(response => {
  removeRepeatUrl(response.config)
  // 对错误代码做处理
  return response
}, error => {
  // 对响应错误做点什么
  console.log('err' + error)
  return Promise.reject(error)
})
export default instance
/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    instance({
      method: 'post',
      url: url,
      data: data,
      headers: { 'Content-Type': 'multipart/form-data' }
    }).then(response => {
      // 对接口错误码做处理
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}
/**
 * get 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get (url, data = {}) {
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: data
    }).then(response => {
      if (response.code <= 0) {
        window.localStorage.removeItem('talent_token_pc')
        let url = window.location.href;
        let base  = url.split('h5')[0]
        instance.get(base+'/user.php?act=logout', {
          params: {}
        }).then(response => {
          router.push({path:'/'})
        }).catch(err => {
          router.push({path:'/'})
        })
      }
      resolve(response)
    }).catch(err => {
      reject(err)
    })
  })
}
/**
 * 封装所有请求
 * @param methed
 * @param url
 * @param data
 * @param headers
 * @returns {Promise}
 */
export function request (methed, url, data = {}, headers) {
  return new Promise((resolve, reject) => {
    instance({
      method: methed || 'post',
      url: url,
      params: methed == 'get' ? data : '',
      data: methed !== 'get' ? qs.stringify(data) : '',
      headers: headers || { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).then(response => {
      // 对接口错误码做处理
      if (response.data.code <= 0) {
        window.localStorage.removeItem('talent_token_pc')
        let url = window.location.href;
        let base  = url.split('h5')[0]
        instance.get(base+'/user.php?act=logout', {
          params: {}
        }).then(response => {
          router.push({path:'/'})
        }).catch(err => {
          router.push({path:'/'})
        })
      }
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}
